<script setup>
/**
 * 登录/注册复合组件：
 * Props：
 * - initialMode: 'login' | 'register' 初始模式
 * Emits：
 * - login-success, register-success
 * 行为：
 * - 登录/注册成功后，dataService 持久化登录状态
 * - 通过路由查询参数 redirect 在登录/注册后返回目标页
 * - 注册成功后自动登录，失败则提示并切换到登录
 */
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { login, register } from '../services/dataService';

// 定义props
const props = defineProps({
  initialMode: {
    type: String,
    default: 'login', // 'login' 或 'register'
    validator: (value) => ['login', 'register'].includes(value)
  }
})

// 定义emit
const emit = defineEmits(['login-success', 'register-success'])

const router = useRouter();
const route = useRoute();
const redirectTarget = route.query.redirect || '/';
const isLoginMode = ref(props.initialMode === 'login');
const isLoading = ref(false);
const errorMessage = ref('');

// 登录表单数据
const loginForm = ref({
  username: '',
  password: ''
});

// 注册表单数据
const registerForm = ref({
  username: '',
  email: '',
  password: ''
});

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value;
  errorMessage.value = '';
};

// 处理登录
const handleLogin = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  try {
    const result = await login(loginForm.value.username, loginForm.value.password);
    if (result.success) {
      emit('login-success', result.user);
      window.dispatchEvent(new Event('storage'));
      router.push(String(redirectTarget));
    } else {
      errorMessage.value = result.message || '登录失败，请检查用户名和密码';
    }
  } catch (error) {
    console.error('登录错误:', error);
    errorMessage.value = '登录过程中出现错误，请稍后重试';
  } finally {
    isLoading.value = false;
  }
};

// 处理注册
const handleRegister = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  if (registerForm.value.password.length < 6) {
    errorMessage.value = '密码长度至少为6位';
    isLoading.value = false;
    return;
  }
  try {
    const result = await register(registerForm.value.username, registerForm.value.password, registerForm.value.email);
    if (result.success) {
      emit('register-success', result.user);
      const loginResult = await login(registerForm.value.username, registerForm.value.password);
      if (loginResult.success) {
        window.dispatchEvent(new Event('storage'));
        router.push(String(redirectTarget));
      } else {
        toggleMode();
        loginForm.value.username = registerForm.value.username;
        errorMessage.value = '注册成功，请登录';
      }
    } else {
      errorMessage.value = result.message || '注册失败，请稍后重试';
    }
  } catch (error) {
    console.error('注册错误:', error);
    errorMessage.value = '注册过程中出现错误，请稍后重试';
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="login-register-container">
    <div class="auth-form-wrapper">
      <div class="auth-header">
        <h2 class="auth-title">{{ isLoginMode ? '花卉系统登录' : '花卉系统注册' }}</h2>
        <p class="auth-subtitle">{{ isLoginMode ? '欢迎回来' : '创建您的账号' }}</p>
      </div>
      
      <!-- 登录表单 -->
      <form v-if="isLoginMode" class="auth-form" @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="login-username" class="form-label">用户名</label>
          <input
            type="text"
            id="login-username"
            v-model="loginForm.username"
            class="form-input"
            placeholder="请输入用户名"
            required
            autocomplete="username"
          />
        </div>
        
        <div class="form-group">
          <label for="login-password" class="form-label">密码</label>
          <input
            type="password"
            id="login-password"
            v-model="loginForm.password"
            class="form-input"
            placeholder="请输入密码"
            required
            autocomplete="current-password"
          />
        </div>
        
        <div class="form-actions">
          <button type="submit" class="auth-button" :disabled="isLoading">
            {{ isLoading ? '登录中...' : '登录' }}
          </button>
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <div class="auth-hint">
          <p>还没有账号？ <button type="button" class="mode-toggle" @click="toggleMode">立即注册</button></p>
          <p v-if="isLoginMode">演示账号：</p>
          <p v-if="isLoginMode">用户名: admin 密码: admin123 (管理员)</p>
          <p v-if="isLoginMode">用户名: user1 密码: user123 (普通用户)</p>
        </div>
      </form>
      
      <!-- 注册表单 -->
      <form v-else class="auth-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="register-username" class="form-label">用户名</label>
          <input
            type="text"
            id="register-username"
            v-model="registerForm.username"
            class="form-input"
            placeholder="请设置用户名"
            required
            autocomplete="username"
          />
        </div>
        
        <div class="form-group">
          <label for="register-email" class="form-label">邮箱</label>
          <input
            type="email"
            id="register-email"
            v-model="registerForm.email"
            class="form-input"
            placeholder="请输入邮箱"
            required
            autocomplete="email"
          />
        </div>
        
        <div class="form-group">
          <label for="register-password" class="form-label">密码</label>
          <input
            type="password"
            id="register-password"
            v-model="registerForm.password"
            class="form-input"
            placeholder="请设置密码（至少6位）"
            required
            minlength="6"
            autocomplete="new-password"
          />
        </div>
        
        <div class="form-actions">
          <button type="submit" class="auth-button" :disabled="isLoading">
            {{ isLoading ? '注册中...' : '注册' }}
          </button>
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <div class="auth-hint">
          <p>已有账号？ <button type="button" class="mode-toggle" @click="toggleMode">立即登录</button></p>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.login-register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.auth-form-wrapper {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin: 0 0 10px 0;
}

.auth-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #555;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

.form-input:focus {
  outline: none;
  border-color: #8E8C41;
  background-color: white;
  box-shadow: 0 0 0 3px rgba(142, 140, 65, 0.1);
}

.form-actions {
  margin-top: 10px;
}

.auth-button {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #8E8C41 0%, #7A7835 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.auth-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(142, 140, 65, 0.3);
}

.auth-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.error-message {
  background-color: #fee;
  color: #c33;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
}

.auth-hint {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 20px;
}

.auth-hint p {
  margin: 8px 0;
}

.mode-toggle {
  background: none;
  border: none;
  color: #8E8C41;
  font-weight: 600;
  cursor: pointer;
  padding: 0;
  font-size: 14px;
  text-decoration: underline;
  transition: color 0.3s ease;
}

.mode-toggle:hover {
  color: #7A7835;
}

@media (max-width: 768px) {
  .auth-form-wrapper {
    padding: 30px 20px;
    margin: 20px 0;
  }
  
  .auth-title {
    font-size: 24px;
  }
  
  .auth-subtitle {
    font-size: 14px;
  }
  
  .form-input {
    padding: 10px 14px;
    font-size: 14px;
  }
  
  .auth-button {
    padding: 12px;
    font-size: 14px;
  }
}
</style>